package com.part2.action.system;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.ajaxanywhere.AAUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.part2.Constants;
import com.part2.action.common.CommonAction;
import com.part2.action.common.Password;
import com.part2.action.common.form.CustomActionForm;
import com.part2.action.common.form.ValueObject;
import com.part2.action.common.validator.Validator;
import com.part2.beans.Users;
import com.part2.business.function.UsersService;

public class LoginAndOutAction extends CommonAction<Users> {

	private final Log logger = LogFactory.getLog(getClass());

	private UsersService usersService;

	public void setUserService(UsersService usersService) {
		this.usersService = usersService;
	}


	// 登录
	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("ready for login ....");
		ActionMessages errors = new ActionMessages();
		ValueObject userVo = ((CustomActionForm) form).getVoa()
				.getValue("User");
		String userId = userVo.getField("name");
		String password = userVo.getField("password");
			if (this.validatorUser(userId, password, errors, request, response)) {
				HttpSession session = request.getSession();
				this.loginServlet(userId, session);
				logger.info("login success !");
				int userType = usersService.findUsersByPrimeKey(userId)
						.getPurview();
				String returnString = "loginUser";
				returnString = this.getReturnPageString(userType, returnString);
				if (returnString.equals("loginAdminUser")) {
					return mapping.findForward("loginAdminUser");
				}
			} else {
				logger.info("login false !");
				this.saveErrors(request, errors);
				return mapping.findForward("error");
		}
		return mapping.findForward("error");
	}

	// 重新登录
//	public ActionForward reLogin(ActionMapping mapping, ActionForm form,
//			HttpServletRequest request, HttpServletResponse response)
//			throws Exception {
//
//		logger.info("ready for reLogin ....");
//
//		ActionMessages errors = new ActionMessages();
//
//		HttpSession session = request.getSession();
//
//		Users user = (Users) session.getAttribute(Constants.USER_IN_SESSION);
//
//		// 判断是否新的 session
//		if (session.isNew() || user == null) {
//			errors.add("you-did-not-login", new ActionMessage(
//					"you-did-not-login"));
//			this.saveErrors(request, errors);
//			return new ActionForward("/index.do");
//		}
//
//		String returnString = "loginUser";
//		return mapping.findForward(returnString);
//	}

	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("run  logout ....");
		HttpSession session = request.getSession();

		logoutServlet(session);
		return mapping.findForward("index");
	}

	private boolean validatorUser(String userId, String password,
			ActionMessages errors, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		if (Validator.isNull(userId)) {
			errors.add("login-id-not-null", new ActionMessage(
					"login-id-not-null"));
			logger.info("id is null");
			return false;
		}
		if (Validator.isNull(password)) {
			errors.add("login-password-not-null", new ActionMessage(
					"login-password-not-null"));
			logger.info("password is null");
			return false;
		}
		Users user = null;
		try {
			user = usersService.findUsersByPrimeKey(userId);
		} catch (Exception e) {
			e.printStackTrace();
			user = null;
		}
		if (user == null) { // recycled? or valid?
			errors.add("login-user-not-exist", new ActionMessage(
					"login-user-not-exist"));
			logger.info("user existed? false");
			return false;
		} else if (!Password.authenticatePassword(user.getPassword(), password)) {
			errors.add("login-password-error", new ActionMessage(
					"login-password-error"));
			logger.info("password?false");
			return false;
		} else {
			if (user.getPurview() == (short) Constants.USER_TYPE_ADMIN) {
				request.getSession().setAttribute("adminUserId",
						user.getUserId());
				request.getSession().setAttribute("adminUserName",
						user.getUserName());
			} else {
				request.getSession().setAttribute("userId", user.getUserId());
				request.getSession().setAttribute("userName",
						user.getUserName());
				request.getSession()
						.setAttribute("userType", user.getPurview());
			}
		}
		return true;
	}

	private String getReturnPageString(int userType, String returnString) {
		switch (userType) {
		case Constants.USER_TYPE_ADMIN:
			logger.info("login admin page...");
			returnString = "loginAdminUser";
			break;
		default:
			returnString = "loginUser";
		}
		return returnString;
	}

	private void loginServlet(String userId, HttpSession session)
			throws Exception {
		Users user = usersService.findUsersByPrimeKey(userId);
		session.setAttribute(USER_IN_SESSION, user);
	}

	private void logoutServlet(HttpSession session) {
		try {
			session.invalidate();
		} catch (Exception ee) {
			ee.printStackTrace();
		}
	}

}
